console.log("start handle md file!");
const mdpdf = require('mdpdf');
const fs = require('fs');
const path = require('path');
 

let results = [];
async function handleMdFile(filePath) {
    try {
        const files = await fs.promises.readdir(filePath, { withFileTypes: true });

        files.forEach(file => {
            if (path.extname(file.name) === 'png') {
                return false;
            }
            if (file.name === 'img') {
                return false;
            }
            if (file.isDirectory()) {
                const newPath = path.join(filePath, file.name);
                handleMdFile(newPath);
            } else if (path.extname(file.name) === '.md') {
                const fp = path.join(filePath, file.name);
                replaceInMarkdownFiles(fp);
                let options = {
                    source: fp,
                    //destination: path.join(__dirname, 'output.pdf'),
                    //styles: path.join(__dirname, 'md-styles.css'),
                    pdf: {
                        format: 'A4',
                        orientation: 'portrait'
                    }
                };
                
                mdpdf.convert(options).then((pdfPath) => {
                    console.log('PDF 路径:', pdfPath);
                }).catch((err) => {
                    console.error(err);
                });
                //转pdf
                //results.push(fp);
            }
        });

    } catch (e) {
        console.error(e);
    }
}
function replaceInMarkdownFiles(filePath) {
    fs.readFile(filePath, 'utf8', (err, content) => {
        if (err) {
            console.error(`Error reading file: ${filePath}`, err);
            return;
        }

        // 定义多个正则表达式和对应的替换内容
        const replacements = [
            { regex: />\s更新.*/g, replacement: '' },
            { regex: />\s原文.*/g, replacement: '' },
            // 可以继续添加更多的替换规则
        ];

        // 对每个替换规则进行处理
        replacements.forEach(replace => {
            content = content.replace(replace.regex, replace.replacement);
        });

        // 将修改后的内容写回文件
        fs.writeFile(filePath, content, 'utf8', (err) => {
            if (err) {
                console.error(`Error writing file: ${filePath}`, err);
                return;
            }
            console.log(`File has been updated: ${filePath}`);
        });
    });
}




async function sleep(ms) {
    return new Promise(resolve => { setTimeout(resolve, ms) })
}
(async () => {
    //let pths = 'D:/yuque-files/download';
    let pths = 'D:/yuque-files/download/Linux/ToolsSoftware/4个好用的Linux监控工具/iftop命令详解及使用场景';
    await handleMdFile(pths);

    console.log("end handle md file!");
    await sleep(100);
    console.log(results);
})();


